package com.tiger.admin.http.login;
import com.tiger.common.IpToAddress;
import com.tiger.common.Jwt;
import org.apache.commons.codec.binary.Hex;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class LoginService {
    private final IpToAddress ipToAddress;

    private final Jwt jwt;

    public LoginService(IpToAddress ipToAddress, Jwt jwt) {
        this.ipToAddress = ipToAddress;
        this.jwt = jwt;
    }

//    public String buildPassword(String password, String salt) {
//        password = sha256Hash(password);
//        return sha256Hash(password + salt);
//    }
//
//    public static String sha256Hash(String input) {
//        try {
//            MessageDigest digest = MessageDigest.getInstance("SHA-256");
//            byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
//            return Hex.encodeHexString(hashBytes).toLowerCase();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    public long getJwtExpire() {
        return jwt.getJwtExpire();
    }

    public String makeToken(long id, long time, String salt) {
        Map<String, Object> payload = new HashMap<>();

        Random rand = new Random();
        int randomNum = rand.nextInt(5) + 3; // 这将生成一个3到10之间的随机数（包括3和10）
        payload.put("k", id);
        payload.put("v", id * randomNum);
        payload.put("time", time);
        payload.put("salt", salt);

        return jwt.createToken(payload);
    }


    public String makeToken(long id, long time) {
        Map<String, Object> payload = new HashMap<>();

        Random rand = new Random();
        int randomNum = rand.nextInt(5) + 3; // 这将生成一个3到10之间的随机数（包括3和10）
        payload.put("k", id);
        payload.put("v", id * randomNum);
        payload.put("time", time);

        return jwt.createToken(payload);
    }

    @Async
    public void ipToLogin(String ip) {
        ipToAddress.convert(ip, true);
    }
}
